var connect=require('connect');
var api=connect();
api.use(users)
    .use(pets)
    .use(errorHandler);

var app=connect();
app.use(hello)
    .use('/api',api)
    .use(errorPage)
    .listen(3003, function () {
        console.log('port 3003',new Date());
    });



function hello(req,res,next){
    if('/hello' == req.url){
        return res.end('Hello.');
    }
    next();
}

var db={
  users:{
      Tom:{
          id:0,
          age:20
      }
  }
};
function users(req,res,next){
    var match=(req.url.match(/^\/user\/(.+)/));
    if(match){
        var user=db.users[match[1]];
        if(user){
            res.setHeader('Content-Type','application/json');
            res.end(JSON.stringify(user));
        }else{
            var err=new Error('User not found.');
            err.notFound=true;
            next(err);
        }
    }else{
        next();
    }
}

function pets(req,res,next){
    if('/pet'==req.url){
        undefindFn();
    }else{
        next();
    }
}

function errorHandler(err,req,res,next){
    console.log(err.stack);
    res.setHeader('Content-Type','application/json');
    if(err.notFound){
        res.statusCode=404;
        res.end(JSON.stringify({error:err.message}));
    }else{
        res.statusCode=500;
        res.end(JSON.stringify({error:'Internal Server Error.'}));
    }
}

function errorPage(err,req,res,next){
    console.log('errorPage:',req.url);
}


